﻿using System;
using System.Windows.Forms;
using AviationSimulator.Interfaces;
using System.IO;
using System.Xml.Serialization;
using AviationSimulator.Properties;

namespace AviationSimulator.DataItems.Mode.Send
{
    public class ImportMode : SendModeBase, IModeSerializable
    {
        public string FilePath { get; set; }

        public void Serialize(string filePath)
        {
            var modeToSerialize = new ImportMode
                                      {
                                          Address = Address,
                                          FilePath = FilePath,
                                          Port = Port,
                                          Period = Period,
                                          SendPeriodically = SendPeriodically
                                      };

            var serializer = new XmlSerializer(typeof (ImportMode));

            using (var streamWriter = new StreamWriter(filePath))
            {
                serializer.Serialize(streamWriter, modeToSerialize);
            }
        }

        public void Deserialize(string filePath)
        {
            var deserializer = new XmlSerializer(typeof (ImportMode));
            ImportMode modeToDeserialize;

            try
            {
                using (var streamReader = new StreamReader(filePath))
                {
                    modeToDeserialize = (ImportMode)deserializer.Deserialize(streamReader);
                }
            }
            catch (InvalidOperationException)
            {
                MessageBox.Show(Resources.CantLoadModeParameters);
                return;
            }

            if (modeToDeserialize == null) return;

            FilePath = modeToDeserialize.FilePath;
            Address = modeToDeserialize.Address;
            Port = modeToDeserialize.Port;
            SendPeriodically = modeToDeserialize.SendPeriodically;
            Period = modeToDeserialize.Period;
        }
    }
}
